﻿using Microsoft.AspNetCore.Cors;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.App_Start;
using WTAppletProjectHTTPS.Models;

namespace WTAppletProjectHTTPS.Controllers
{
    [EnableCors("*")]
    public class TokenInitializationController : ApiController
    {
        // POST api/<controller>
        public class FZ
        {
            public string MM { get; set; }
        }
        public async Task<HttpResponseMessage> Post([FromBody] FZ value)
        {
            ReturnObject RO = new ReturnObject();
            if (value.MM != "HSY"+DateTime.Now.ToString("yyyyMMdd"))
            {
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "查询参数无效";
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }
            var token = WebApiApplication.TK;
            //验证令牌是否过期
            var jwtHandler = new JwtSecurityTokenHandler();
            var jwtToken = jwtHandler.ReadJwtToken(token);
            var expClaim = jwtToken.Claims.FirstOrDefault(claim => claim.Type == "exp");
            var expTime = DateTimeOffset.FromUnixTimeSeconds(long.Parse(expClaim.Value)).UtcDateTime;
            var currentTime = DateTime.UtcNow;
            if (currentTime >= expTime)
            {
                token = TokenManager.GenerateToken(ConfigurationManager.AppSettings["JwtSecret"]);
            }

            RO.Status = HttpStatusCode.OK;
            RO.Message = "OK";
            RO.Data = token;
            return Request.CreateResponse(HttpStatusCode.OK, RO);
        }
    }
}